$(function(){
    $(".page").bind("click",function(){ $(".pageBoxBg").toggle();});
    $(".page").click(function(){
        $(".Mbottom").toggleClass("datiBottom");
    });
    $(document).click(function(e){
        var hasDatiBottom = $(".Mbottom").hasClass("datiBottom");
        if( $(e.target).closest('.pageBox').length == 0 && $(e.target).closest('.Mbottom').length == 0 && hasDatiBottom){
            $(".page").click();
        }
    });
    initSpecialPracticeData();
    initHtml();
    //up, right, down, left为四个回调函数，分别处理上下左右的滑动事件
    EventUtil.listenTouchDirection(document,true,null,left,null,next);
    /*** 点击选项 记录选项*/
    $("body").on("click","input[name='dx']",function () {
        var currentQ = currentQuestion();
        var number = parseInt($(".pageNum").first().text());
        var size = parseInt($(".size").first().text());
        var specialPracticeItem = JSON.parse(localStorage.getItem("specialPracticeItem"));
        if(currentQ.questionType != 2 ){
            specialPracticeItem[number-1].hisOption=$(this).val();
            if($(this).val() == currentQ.questionAnswer){
                $("#dui").text((parseInt($("#dui").text())+1));
                $(".timuBox li").eq(number-1).attr("class","correctTi");
                specialPracticeItem[number-1].isPass = 1;
                localStorage.setItem("specialPracticeItem",JSON.stringify(specialPracticeItem));
                if(number<size){
                    setTimeout(function () {
                        setQuestion(number);
                    },500);
                }
            }else{
                $("#cuo").text((parseInt($("#cuo").text())+1));
                $(".timuBox li").eq(number-1).attr("class","wrongTi");
                specialPracticeItem[number-1].isPass = 0;
                localStorage.setItem("specialPracticeItem",JSON.stringify(specialPracticeItem));
                /*errorSave(specialPracticeItem[number-1]);*/
                setQuestion(number-1);
            }
            if(number == size){
                setQuestion(number-1);
            }
        }else{
            var hisOption = "";
            $("input[name='dx']:checked").each(function (n) {
                hisOption += ","+$(this).val();
            });
            hisOption = hisOption.substr(1);
            if(hisOption == currentQ.questionAnswer){
                $(".timuBox li").eq(number-1).attr("class","correctTi");
                specialPracticeItem[number-1].isPass = 1;
            }else{
                $(".timuBox li").eq(number-1).attr("class","wrongTi");
                specialPracticeItem[number-1].isPass = 0;
            }
            specialPracticeItem[number-1].hisOption=hisOption;
            localStorage.setItem("specialPracticeItem",JSON.stringify(specialPracticeItem));
        }
    });

    /*** 选项卡点击事件*/
    $("body").on("click",".timuBox li",function(){
        var number = parseInt($(this).text());
        setQuestion(number-1);
    });

    /*** 多选题点击确认*/
    $("body").on("click",".confirm-btn",function () {
        var currentQ = currentQuestion();
        var number = parseInt($(".pageNum").first().text());
        var size = parseInt($(".size").first().text());
        var hisOption = "";
        $("input[name='dx']:checked").each(function (n) {
            hisOption += ","+$(this).val();
        });
        hisOption = hisOption.substr(1);
        if(hisOption == currentQ.questionAnswer){
            $("#dui").text((parseInt($("#dui").text())+1));
            if(number<size){
                setTimeout(function () {
                    setQuestion(number);
                },500)
            }
        }else{
            $("#cuo").text((parseInt($("#cuo").text())+1));
            /*errorSave(currentQ);*/
            setQuestion(number-1);
        }
        if(number==size){
            setQuestion(number-1);
        }
    });

    /**
     * 清空题目
     */
    $("#clear_questions").click(function(){
        window.localStorage.removeItem("specialPracticeItem");
        window.localStorage.removeItem("specialIndex"+getQueryString("specialId"));
        initSpecialPracticeData();
        window.location.reload();
    })
});

function initSpecialPracticeData() {
    //获取所有题
    /*$.get("/mp/question/getSpecialQuestion",function (result) {
        if(result.code==0){
            var questions = result.data;
            if(questions.length==0){
                $("body").html('<img src="images/nothing.png" style="width: 100%;position: fixed;top: 23%">');
            }
            var specialPracticeItem = JSON.parse(window.localStorage.getItem("specialPracticeItem"));
            if(!specialPracticeItem || questions.length != specialPracticeItem.length){
                localStorage.removeItem("specialIndex"+getQueryString("specialId"));
                localStorage.setItem("specialPracticeItem",JSON.stringify(questions));
            }
        }else {
            layer.open({
                content: result.msg
                ,skin: 'msg'
                ,time: 2 //2秒后自动关闭
            });
        }
    });*/
    $.ajax({
        url:"/mp/question/getSpecialQuestion",
        type:"get",
        async:false,
        dataType:"json",
        success:function (result) {
            var questions = result.data;
            if(questions.length==0){
                $("body").html('<img src="images/nothing.png" style="width: 100%;position: fixed;top: 23%">');
            }
            var specialPracticeItem = JSON.parse(window.localStorage.getItem("specialPracticeItem"));
            if(!specialPracticeItem || questions.length != specialPracticeItem.length){
                localStorage.removeItem("specialIndex"+getQueryString("specialId"));
                localStorage.setItem("specialPracticeItem",JSON.stringify(questions));
            }
        }
    });
}

function left(){
    var currentPage = parseInt($(".pageNum").first().text());
    if((currentPage)-1>0){
        setQuestion(currentPage-2);
    }
}
function next(){
    var currentPage = parseInt($(".pageNum").first().text());
    var total = parseInt($(".size").first().text());
    if(currentPage != total){
        setQuestion(currentPage);
    }
}

/*** 初始化页面*/
function initHtml(){
    var specialPracticeItem = JSON.parse(window.localStorage.getItem("specialPracticeItem"));
    $(".size").text(specialPracticeItem.length);
    var html = "";
    var dui = 0;
    var cuo = 0;
    for(var i in specialPracticeItem){
        if(specialPracticeItem[i].isPass==0){
            cuo += 1;
            html+='<li class="wrongTi iphoneModel">'+(parseInt(i)+1)+'</li>';
        }else if(specialPracticeItem[i].isPass==1){
            html+='<li class="correctTi iphoneModel">'+(parseInt(i)+1)+'</li>';
            dui += 1;
        }else{
            html+='<li class="iphoneModel">'+(parseInt(i)+1)+'</li>';
        }
    }
    $(".timuBox").html(html);
    $("#dui").text(dui);
    $("#cuo").text(cuo);
    var item = window.localStorage.getItem("specialIndex"+getQueryString("specialId"));
    if(item){
        setQuestion(parseInt(item));
    }else{
        setQuestion(0);
    }
}

//设置页面题目
function setQuestion(n) {
    window.localStorage.setItem("specialIndex"+getQueryString("specialId"),n);
    var specialPracticeItem = JSON.parse(window.localStorage.getItem("specialPracticeItem"));
    var optionArr = ["A","B","C","D","E","F"];
    var question = specialPracticeItem[n];
    var questionArr = formatArr(question);
    var headImg = "";
    var html = "";
    var optionsHtml = "";
    //多选
    if(question.questionType == 2){//多选
        headImg = "/mp/images/duoxuan.png";
    }else if(question.questionType == 0){//判断
        headImg = "/mp/images/pd.png";
    }else{
        headImg = "/mp/images/dx.png";
    }
    if(question.hisOption){
        $("#questionAnalysis").show();
    }else{
        $("#questionAnalysis").hide();
    }
    if(question.isPass == 1){
        $("#isPass").text("答对了");
        $("#isPass").attr("style","margin-bottom: 8px;");
    }else if(question.isPass == 0){
        $("#isPass").text("答错了");
        $("#isPass").attr("style","margin-bottom: 8px;color:#fb6e50");
    }
    if(question.questionType == 2){//多选
        var flag = false;
        var hisOption = question.hisOption;
        var split;
        if(hisOption){//如果已经选择过答案
            split = hisOption.split(",");
            flag = true;
        }
        for(var i in questionArr){
            if(questionArr[i].trim()!="" && questionArr[i]!=null){
                if(flag && split.indexOf(optionArr[i])>-1){
                    optionsHtml += '<div class="popCheckOne">'+
                        '<input type="checkbox" value="'+optionArr[i]+'" name="dx" id="'+optionArr[i]+'" checked disabled>'+
                        '<label  for="'+optionArr[i]+'" class="col3">'+optionArr[i]+"."+questionArr[i]+'</label>'+
                        '</div>';
                }else if(flag){
                    optionsHtml += '<div class="popCheckOne">'+
                        '<input type="checkbox" value="'+optionArr[i]+'" name="dx" id="'+optionArr[i]+'" disabled>'+
                        '<label  for="'+optionArr[i]+'" class="col3">'+optionArr[i]+"."+questionArr[i]+'</label>'+
                        '</div>';
                }else{
                    optionsHtml += '<div class="popCheckOne">'+
                        '<input type="checkbox" value="'+optionArr[i]+'" name="dx" id="'+optionArr[i]+'">'+
                        '<label  for="'+optionArr[i]+'" class="col3">'+optionArr[i]+"."+questionArr[i]+'</label>'+
                        '</div>';
                }
            }
        }
        if(!flag){
            optionsHtml += '<input class="confirm-btn" type="button" value="确认答案">';
        }
    }else{
        optionsHtml += '<div class="singleRadio padd20">';
        for(var i in questionArr){
            if(questionArr[i].trim()!="" && questionArr[i]!=null){
                if(question.hisOption == optionArr[i]){
                    optionsHtml += '<div class="radios">'+
                        '<input type="radio" value="'+optionArr[i]+'" name="dx" id="'+optionArr[i]+'" checked disabled>'+
                        '<label class="radioStyle" for="'+optionArr[i]+'">'+optionArr[i]+"."+questionArr[i]+'</label>'+
                        '</div>';
                }else if(question.hisOption){
                    optionsHtml += '<div class="radios">'+
                        '<input type="radio" value="'+optionArr[i]+'" name="dx" id="'+optionArr[i]+'" disabled>'+
                        '<label class="radioStyle" for="'+optionArr[i]+'">'+optionArr[i]+"."+questionArr[i]+'</label>'+
                        '</div>';
                }else{
                    optionsHtml += '<div class="radios">'+
                        '<input type="radio" value="'+optionArr[i]+'" name="dx" id="'+optionArr[i]+'">'+
                        '<label class="radioStyle" for="'+optionArr[i]+'">'+optionArr[i]+"."+questionArr[i]+'</label>'+
                        '</div>';
                }
            }
        }
        optionsHtml += '</div>';
    }
    html += '<p class="fsSmall30 col3 topicItem padd20"><img src="'+headImg+'" alt="" class="dxIcon">'+question.questionContent+'</p>'+optionsHtml;
    $("#content").html(html);
    $("#answer").text('正确答案：'+question.questionAnswer);
    $(".answerDetail p").text('答案解析：'+question.questionAnalysis);
    $(".pageNum").text(n+1);
    window.scrollTo(0,0);
    $("#content").hide();
    $("#content").fadeIn(500);
}

function currentQuestion() {
    var specialPracticeItem = JSON.parse(window.localStorage.getItem("specialPracticeItem"));
    var pageNum = parseInt($(".pageNum").first().text())-1;
    return specialPracticeItem[pageNum];
}

function formatArr(question) {
    var arr = [];
    arr.push(question.optionA);
    arr.push(question.optionB);
    arr.push(question.optionC);
    arr.push(question.optionD);
    arr.push(question.optionE);
    arr.push(question.optionF);
    return arr;
}

